import React, {useMemo, useRef, useState} from "react";
import {Col, Form, Input, Modal, Popover, Radio, Row, Segmented, TreeSelect} from "antd";
import {globalMessageApi} from "@/components/OpComponent/Message";
import SelectIcon from "@/components/SelectIcon";
import Icon, * as icons from "@ant-design/icons";
import {addMenuUrl, getAllMenuListUrl, updateMenuUrl} from "@/api/system/menu.ts";
import {handleTree} from "@/utils/tree.ts";
import * as customIcons from "@/assets/icon";


export default React.forwardRef((props: any, ref: any) => {

    const {
        getList
    } = props
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false)

    const [menuType, setMenuType] = useState("M")

    const [form] = Form.useForm()
    const [formValues, setFormValues] = useState<any>();
    const [hovered, setHovered] = useState(false);
    const [menuOptions, setMenuOptions] = useState<any[]>([])
    const [iconValue, setIconValue] = useState<any>(undefined)
    const selectIconRef = useRef<any>()
    const iconList = useMemo<any[]>((): any => {
        // 合并 customIcons 和
        return {...customIcons, ...icons}
    }, [])

    const handleOk = () => {
        form.validateFields().then((values) => {
            if (isModalEdit) {
                updateMenuUrl({
                    ...values,
                    icon: iconValue,
                    menuId: formValues?.menuId,
                }).then((res: any) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })
            } else {
                addMenuUrl({
                    ...values,
                    icon: iconValue,
                }).then((res) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })

            }
        })
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        setHovered(false)
    }


    /** 查询菜单下拉树结构 */
    function getTreeSelect() {
        getAllMenuListUrl(null).then(response => {
            const menu: any = {menuId: 0, menuName: "主类目", children: []};
            menu.children = handleTree(response.data, "menuId");
            setMenuOptions([
                menu
            ])
        });
    }

    const editModal = async (data: any) => {
        if (menuOptions && menuOptions.length == 0) await getTreeSelect()
        setIsModalEdit(true)
        setFormValues(data);
        form.setFieldsValue(data)
        setIconValue(data?.icon)
        setMenuType(data?.menuType)
        setIsModalOpen(true)
    }

    const addModal = async (data: any) => {
        if (menuOptions && menuOptions.length == 0) await getTreeSelect()
        setIsModalEdit(false)
        setMenuType('M')
        setIsModalOpen(true)
        form.setFieldsValue({
            parentId: data?.menuId | 0,
            menuType: 'M',
            isFrame: '1',
            status: '0',
            visible: '0',
            isCache: '0'
        })
    }

    React.useImperativeHandle(ref, () => ({
        editModal: editModal,
        addModal: addModal,
    }))
    return <Modal title={isModalEdit ? "编辑菜单" : "新增菜单"}
                  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                  modalRender={(dom) => (
                      <Form
                          wrapperCol={{span: 14}}
                          form={form}
                          initialValues={formValues}>
                          {dom}
                      </Form>
                  )}
                  width={600}
                  onClose={handleCancel}
    >
        <Row>
            <Col span={24}>
                <Form.Item name={"parentId"} label="上级菜单">
                    <TreeSelect
                        showSearch
                        style={{width: '100%'}}
                        dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                        placeholder="请选择上级菜单"
                        treeDefaultExpandAll
                        treeData={menuOptions}
                        fieldNames={{label: "menuName", value: "menuId", children: "children"}}
                    />
                </Form.Item>
            </Col>
            <Col span={24}>
                <Form.Item name={"menuType"} label="菜单类型">
                    <Segmented<string> options={[
                        {label: "目录", value: "M"},
                        {label: "菜单", value: "C"},
                        {label: "按钮", value: "F"},
                    ]}
                                       onChange={(value: string) => {
                                           setMenuType(value)
                                       }}
                    />
                </Form.Item>
            </Col>

            {
                (menuType == "C" || menuType == "M") &&
                <Col span={24}>
                    <Form.Item name={"icon"} label="菜单图标">
                        <Popover
                            placement="bottom"
                            arrow={false}
                            content={
                                <SelectIcon style={{width: 500}} ref={selectIconRef} setValue={setIconValue}
                                            setHovered={setHovered}/>
                            }
                            title="菜单图标"
                            trigger="click"
                            open={hovered}
                            onOpenChange={() => setHovered(false)}
                        >
                            <Input placeholder="请选择图标" readOnly
                                   prefix={<Icon component={iconList[iconValue]}/>}
                                   value={iconValue}
                                   onClick={() => setHovered(true)}/>
                        </Popover>
                    </Form.Item>
                </Col>
            }

            <Col span={12}>
                <Form.Item name={"menuName"} label="菜单名称"
                           rules={[{required: true, message: '请输入菜单名称!'}]}>
                    <Input placeholder="请输入菜单名称"/>
                </Form.Item>
            </Col>
            <Col span={12}>
                <Form.Item name={"orderNum"} label="显示排序"
                           rules={[{required: true, message: '请输入显示排序!'}]}>
                    <Input type="number" placeholder="请输入显示排序"/>
                </Form.Item>
            </Col>

            {(menuType === "M" || menuType === "C") && <Col span={12}>
                <Form.Item name={"isFrame"} label="是否外链">
                    <Radio.Group>
                        <Radio value="0">是</Radio>
                        <Radio value="1">否</Radio>
                    </Radio.Group>
                </Form.Item>
            </Col>}
            {(menuType === "M" || menuType === "C") && <Col span={12}>
                <Form.Item name={"path"} label="路由地址"
                           rules={[{required: true, message: '请输入路由地址!'}]}>
                    <Input placeholder="请输入路由地址"/>
                </Form.Item>
            </Col>}


            {menuType === "C" && <Col span={12}>
                <Form.Item name={"component"} label="组件路径">
                    <Input placeholder="请输入组件路径"/>
                </Form.Item>
            </Col>}
            {(menuType === "C" || menuType === "F") && <Col span={12}>
                <Form.Item name={"perms"} label="权限字符">
                    <Input placeholder="请输入权限字符"/>
                </Form.Item>
            </Col>}
            {menuType === "C" && <Col span={12}>
                <Form.Item name={"query"} label="路由参数">
                    <Input placeholder="请输入路由参数"/>
                </Form.Item>
            </Col>}
            {menuType === "C" && <Col span={12}>
                <Form.Item name={"isCache"} label="是否缓存">
                    <Radio.Group>
                        <Radio value="0">缓存</Radio>
                        <Radio value="1">不缓存</Radio>
                    </Radio.Group>
                </Form.Item>
            </Col>
            }


            {(menuType === "M" || menuType === "C") && <Col span={12}>
                <Form.Item name={"visible"} label="显示状态">
                    <Radio.Group>
                        <Radio value="0">显示</Radio>
                        <Radio value="1">隐藏</Radio>
                    </Radio.Group>
                </Form.Item>
            </Col>}

            <Col span={12}>
                <Form.Item name={"status"} label="菜单状态">
                    <Radio.Group>
                        <Radio value={"0"}>正常</Radio>
                        <Radio value={"1"}>停用</Radio>
                    </Radio.Group>
                </Form.Item>
            </Col>
        </Row>
    </Modal>
})
